package com.itheima.aop;

import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.entity.OperateLog;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Component
@Aspect
@Slf4j
public class OperateLogAop {
    @Autowired
    private OperateLogMapper operateLogMapper;
    @Autowired
    private HttpServletRequest request;

    @Around("@annotation(com.itheima.annotation.Log) && execution(* com.itheima.controller.*.*(..))")
    public Object OperateLog(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("日志记录类开始执行...");
        OperateLog operateLog = new OperateLog();
        Long startTime = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        Long endTime = System.currentTimeMillis();

        operateLog.setCostTime(endTime-startTime);
        operateLog.setClassName(joinPoint.getTarget().getClass().getName());
        operateLog.setMethodName(joinPoint.getSignature().getName());
        operateLog.setMethodParams(Arrays.toString(joinPoint.getArgs()));
        operateLog.setOperateTime(LocalDateTime.now());
        operateLog.setReturnValue(result.toString());

        String token = request.getHeader("token");
        Claims claims = JwtUtils.parseJWT(token);
        Integer id = (Integer) claims.get("id");
        operateLog.setOperateEmpId(id);
        operateLogMapper.insert(operateLog);

        return result;
    }
}
